import axios from "axios"
import store from "@/store"
import {message} from "ant-design-vue"
import router from "@/router";
import config from "@/config/index";
// 修-改
axios.defaults.baseURL = process.env.NODE_ENV === 'production' ? config.urlPath : '/api';
// axios.defaults.baseURL = process.env.NODE_ENV === 'production' ? '/api' : '/api';
axios.defaults.timeout = 60*1000*10


// 发起请求之前的拦截器
axios.interceptors.request.use(
    config => {
        // 加载进度条
        store.commit("load/setloadding", true)
        // 如果有token 就携带tokon
        const userinfo = store.getters["userinfo/getUserInfo"]
        if (userinfo) {
            config.headers.token = userinfo.token
        }
        return config
    },
    error => Promise.reject(error)
)

// 响应拦截器
axios.interceptors.response.use(
    response => {
        // 隐藏进度条
        store.commit("load/setloadding", false)
        const res = response.data
        if (response.status !== 200) {
            return Promise.reject(new Error(res))
        } else {
            // 判断后端返回状态码
            if(typeof res.status != "undefined")
                switch(res.status){
                    case 6006: // token无效
                        store.commit("userinfo/logout")
                        router.push("/login")
                        return
                    default:
                        break
                }
            return res
        }
    },
    error => {
        // 隐藏进度条
        store.commit("load/setloadding", false)
        message.error('数据传输异常')
        const { response } = error
        const status = response.status
        switch(status){
            case 404:
                break
            default:
                break
        }
        return Promise.reject(error)
    }
)

export default axios

